<template>
  <div class="config-container">
    <el-form :model="formData" label-width="120px">
      <el-row :gutter="20">
        <el-alert
          title="条件公式 = {字段}{关系}{值}"
          type="warning"
          :closable="false"
          style="margin-bottom: 20px"
        />
        <el-col :span="12">
          <el-form-item label="条件公式(IF)">
            <div class="custom-editor">
              <template v-if="formData.condition.length">
                <draggable
                  v-model="formData.condition"
                  item-key="id"
                  animation="300"
                  :disabled="false"
                >
                  <template #item="{ element, index }">
                    <span class="condition-item" :class="{ 'selected-item': element.isSelected }">
                      <template v-if="element.type === 'custom' && element.isEditing">
                        <el-input
                          v-model="element.value"
                          size="small"
                          style="width: 120px"
                          @blur="handleCustomValueBlur(element)"
                          @keyup.enter="handleCustomValueBlur(element)"
                          v-focus
                        />
                      </template>
                      <template v-else>
                        {{ element.value }}
                        <!-- 自定义值 -->
                        <i
                          v-if="element.type === 'custom'"
                          class="edit-icon el-icon-edit"
                          @click.stop="handleEditCustomValue(element)"
                        >
                          <el-icon><Edit /></el-icon>
                        </i>
                      </template>
                      <i class="delete-icon" @click.stop="removeItem(index)">×</i>
                    </span>
                  </template>
                </draggable>
              </template>
              <template v-else>
                <div class="placeholder">暂无条件公式，请选择</div>
              </template>
            </div>
            <el-button type="primary" @click="handleAddCustomValue" style="margin-top: 10px">
              增加值
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结果(THEN)">
            <el-input v-model="formData.result" type="textarea" :rows="4" placeholder="输入结果" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="field-select">
        <el-form-item label="字段选择">
          <el-select v-model="selectedField" placeholder="请选择字段" style="width: 200px">
            <el-option label="病" value="病" />
          </el-select>
          <el-button style="margin-left: 20px" type="primary" @click="handleAddField"
            >查询</el-button
          >
        </el-form-item>
      </div>

      <el-table :data="fieldList" border style="width: 100%; margin-top: 20px">
        <el-table-column prop="name" label="字段名" align="center" />
        <el-table-column prop="type" label="字段位置" align="center" />
        <el-table-column prop="desc" label="字段注释" align="center" />
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleChooseField(scope)">
              {{
                formData.condition.some((item) => item.value === scope.row.name)
                  ? '取消选择'
                  : '选择'
              }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="symbol-select">
        <h4>符号选择</h4>
        <div class="symbol-list">
          <span
            v-for="symbol in symbols"
            :key="symbol"
            class="symbol-item"
            @click="insertSymbol(symbol)"
          >
            {{ symbol }}
          </span>
        </div>
      </div>

      <div class="relation-select">
        <h4>关系选择</h4>
        <div class="relation-list">
          <span
            v-for="relation in relations"
            :key="relation"
            class="relation-item"
            :class="{ selected: selectedRelation === relation }"
            @click="insertRelation(relation)"
          >
            {{ relation }}
          </span>
        </div>
      </div>

      <div class="value-select">
        <h4>值域选择</h4>
        <el-select v-model="selectedValue" placeholder="糖尿病" style="width: 200px">
          <el-option label="糖尿病" value="糖尿病" />
        </el-select>
        <el-button type="primary" @click="handleSearch" style="margin-left: 20px">查询</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>

      <el-table :data="valueList" border style="width: 100%; margin-top: 20px">
        <el-table-column prop="name" label="值域名称" align="center" />
        <el-table-column prop="operator" label="操作人" align="center" />
        <el-table-column prop="time" label="操作日期" align="center" />
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" @click="handleChooseValue(scope)">
              {{
                formData.condition.some((item) => item.value === scope.row.name)
                  ? '取消选择'
                  : '选择'
              }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="button-group">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-form>

    <el-dialog
      v-model="dialogVisible"
      title="值域配置"
      width="800px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <ValueDomain
        :edit-data="editData"
        @cancel="handleDialogCancel"
        @submit="handleDialogSubmit"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import ValueDomain from '../components/ValueDomain.vue'
import draggable from 'vuedraggable'
import { Edit } from '@element-plus/icons-vue'

const vFocus = {
  mounted: (el) => el.querySelector('input').focus(),
}

const route = useRoute()
const router = useRouter()
const optionType = ref(route.query.type || '')

const formData = reactive({
  condition: [],
  result: '',
})

const symbols = ['+', '-', '*', '/', '【', '】', '√￣', '∑', '(', ')', '计数']

const relations = [
  '包含',
  '不包含',
  '除外',
  '为空',
  '不为空',
  '等于',
  '不等于',
  '大于等于',
  '小于等于',
  '大于',
  '并且',
  '或',
]

const selectedField = ref('')
const fieldList = ref([
  { name: '床位费', type: '医保结算清单', desc: '', remark: '' },
  { name: '护理费', type: '医保结算清单', desc: '', remark: '' },
  { name: '主要诊断', type: '出院记录', desc: '', remark: '' },
])

const selectedValue = ref('')
const valueList = ref([
  {
    name: '糖尿病诊断项',
    operator: '管理员A',
    time: '20241219 14:00',
    remark: '糖尿病相关诊断列表',
  },
])

const dialogVisible = ref(false)
const editData = ref({})

const handleAddField = () => {}

const handleChooseField = (scope) => {
  const fieldName = scope.row.name
  const existingItem = formData.condition.find(
    (item) => item.value === fieldName && item.type === 'field',
  )

  if (existingItem) {
    const index = formData.condition.indexOf(existingItem)
    formData.condition.splice(index, 1)
    return '选择'
  } else {
    formData.condition.push({
      id: Date.now(),
      value: fieldName,
      type: 'field',
      isSelected: true,
    })
    return '取消选择'
  }
}

const insertSymbol = (symbol) => {
  formData.condition.push({
    id: Date.now(),
    value: symbol,
    type: 'symbol',
    isSelected: true,
  })
}

const selectedRelation = ref('')

const insertRelation = (relation) => {
  const oldRelationIndex = formData.condition.findIndex((item) => item.type === 'relation')
  if (oldRelationIndex !== -1) {
    formData.condition.splice(oldRelationIndex, 1)
  }

  formData.condition.push({
    id: Date.now(),
    value: relation,
    type: 'relation',
    isSelected: true,
  })

  selectedRelation.value = relation
}

const handleSearch = () => {}

const handleAdd = () => {
  editData.value = ''
  editData.pageNo = 1
  dialogVisible.value = true
}

const handleEdit = (row) => {
  editData.value = row
  dialogVisible.value = true
}

const handleView = (row) => {
  editData.value = row
  dialogVisible.value = true
}

const handleAddCustomValue = () => {
  formData.condition.push({
    id: Date.now(),
    value: '',
    type: 'custom',
    isSelected: true,
    isEditing: true,
  })
}

const handleCustomValueBlur = (element) => {
  if (!element.value.trim()) {
    const index = formData.condition.findIndex((item) => item.id === element.id)
    if (index !== -1) {
      formData.condition.splice(index, 1)
    }
    return
  }
  element.isEditing = false
}

const handleEditCustomValue = (element) => {
  element.isEditing = true
}

const validateBrackets = (condition) => {
  const hasLeftSquare = condition.some((item) => item.value === '【')
  const hasRightSquare = condition.some((item) => item.value === '】')

  if ((hasLeftSquare && !hasRightSquare) || (!hasLeftSquare && hasRightSquare)) {
    ElMessage.error('【】必须成对出现')
    return false
  }

  const hasLeftRound = condition.some((item) => item.value === '(')
  const hasRightRound = condition.some((item) => item.value === ')')

  if ((hasLeftRound && !hasRightRound) || (!hasLeftRound && hasRightRound)) {
    ElMessage.error('()必须成对出现')
    return false
  }

  return true
}

const handleSubmit = () => {
  console.log('提交的数据：', formData.condition)
  if (!formData.condition.length) {
    ElMessage.error('请添加条件公式')
    return
  }

  if (!validateBrackets(formData.condition)) {
    return
  }

  ElMessage.success(optionType.value === 'add' ? '新增成功' : '编辑成功')
}

const handleCancel = () => {
  router.back()
}

const removeItem = (index) => {
  formData.condition.splice(index, 1)
}

const handleChooseValue = (scope) => {
  const valueName = scope.row.name
  const existingItem = formData.condition.find(
    (item) => item.value === valueName && item.type === 'value',
  )

  if (existingItem) {
    const index = formData.condition.indexOf(existingItem)
    formData.condition.splice(index, 1)
    return '选择'
  } else {
    formData.condition.push({
      id: Date.now(),
      value: valueName,
      type: 'value',
      isSelected: true,
    })
    return '取消选择'
  }
}

const handleDialogCancel = () => {
  editData.value = {}
  dialogVisible.value = false
}

const handleDialogSubmit = (data) => {
  console.log('提交的数据：', data)
  dialogVisible.value = false
  ElMessage.success('新增成功')
}

onMounted(() => {
  if (optionType.value === 'edit') {
  }
})
</script>

<style lang="less" scoped>
.config-container {
  padding: 20px;

  .field-select,
  .symbol-select,
  .relation-select,
  .value-select {
    margin: 20px 0;
  }

  .button-group {
    margin-top: 20px;
    text-align: center;
  }

  h4 {
    margin: 10px 0;
  }

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  .el-table {
    margin: 10px 0;
  }

  :deep(.el-button) {
    &:focus,
    &:focus-visible {
      outline: none !important;
      box-shadow: none !important;
    }
  }
}

.custom-editor {
  width: 100%;
  min-height: 95px;
  padding: 5px 11px;
  background-color: rgb(242, 242, 242);
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  line-height: 2;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-all;
  overflow-y: auto;

  .placeholder {
    color: #909399;
    font-size: 14px;
    line-height: 75px;
    text-align: center;
  }

  span {
    display: inline-block;
    margin: 2px 4px;
    padding: 2px 6px;
    border-radius: 4px;
    transition: all 0.3s;

    &.selected-item {
      cursor: pointer;
      background-color: #409eff;
      color: #ffffff;
    }
  }

  .condition-item {
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin: 4px 6px;
    padding: 6px 24px 6px 12px;
    min-height: 36px;
    border-radius: 4px;
    transition: all 0.3s;
    font-size: 15px;

    .delete-icon {
      position: absolute;
      right: 5px;
      top: -7px;
      font-style: normal;
      font-size: 14px;
      cursor: pointer;
      color: #fff;
      padding: 2px;
    }

    .edit-icon {
      position: absolute;
      right: 2px;
      bottom: -5px;
      font-style: normal;
      font-size: 12px;
      cursor: pointer;
      color: #fff;
      padding: 2px;
    }

    &.selected-item {
      background-color: #409eff;
      color: #ffffff;

      .delete-icon,
      .edit-icon {
        color: #fff;
      }
    }
  }
}

:deep(.el-form-item__content) {
  line-height: 1;
}

.symbol-list,
.relation-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.symbol-item,
.relation-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 40px;
  height: 40px;
  padding: 0 15px;
  border: 2px solid #dcdfe6;
  border-radius: 6px;
  font-size: 15px;
  color: #606266;
  background-color: #ffffff;
  cursor: pointer;
  user-select: none;
  transition: all 0.3s;

  &:hover {
    color: #409eff;
    border-color: #c6e2ff;
    border-width: 2px;
    background-color: #ecf5ff;
  }

  &:active {
    color: #3a8ee6;
    border-color: #3a8ee6;
    border-width: 2px;
  }

  &.selected {
    color: #409eff;
    border-color: #409eff;
    background-color: #ecf5ff;
  }
}

.relation-item {
  min-width: 80px;

  &.selected {
    color: #409eff;
    border-color: #409eff;
    background-color: #ecf5ff;
  }
}
</style>
